﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;

namespace Demo
{
    public class DemoUtility
    {
        public static String GetExtensionFromFilename(String filename)
        {
            if (string.IsNullOrEmpty(filename)) throw new ArgumentOutOfRangeException("filename");
            int lastIndex = filename.LastIndexOf('.');

            if ((lastIndex >= 0) == false) throw new InvalidOperationException("(lastIndex >= 0)) == false");

            return filename.Substring(lastIndex);
        }

        public static String ConstructQueryString(NameValueCollection parameters)
        {
            List<String> items = new List<String>();

            foreach (String name in parameters)
                items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name])));

            return String.Join("&", items.ToArray());
        }

        public static String GetUrlWithParameter(String original, String parameter, String value)
        {
            String queryString = null;

            if (original.Contains("?"))
            {
                int index = original.IndexOf("?");
                queryString = original.Substring(index + 1);
                original = original.Substring(0, index);
            }

            NameValueCollection query = null;

            if (!string.IsNullOrEmpty(queryString))
                query = HttpUtility.ParseQueryString(queryString);
            else
                query = new NameValueCollection();
            
            query[parameter] = value;

            queryString = ConstructQueryString(query);

            return original + "?" + queryString;
        }
    }
}